<template>
  <div class="projectBuildStup" v-title data-title="孵化立项页面">
    
    <a-modal
      title="消息提醒"
      :visible="toDelVisible"
      :confirm-loading="false"
      @ok="toDelOk"
      @cancel="toDelVisible = false"
    >
      删除后将无法再查看该孵化立信息，确定删除？
    </a-modal>
    
    <home-nav :userData="userinfo"></home-nav>
    <div class="navigator" style="display: flex">
      <div class="floatNav">
        <a-button    
          v-if="submitAndDel && !isProjectMember"     
          type="primary"          
          @click="submitProject()"
          :loading="btnLoading"
          >提交审批</a-button
        >
        <a-button
          v-if="submitAndDel && !isProjectMember"
          type="default"
          @click="toDelVisible = true"
          :loading="btnLoading"
          >删除项目</a-button
        >
      </div>
      <div :class="{ 'left-content': true, 'left-move200': !submitAndDel }">
        <ul>
          <li
            v-show="!(changeId || changeInit) || changeModels.indexOf(0) > -1"
            :class="{ clickShow: pageId == 0, dengerBackGround: dengerTab.indexOf('baseInfo') > -1 }"
            @click="handleTogglePage(0)"
          >
            <a-icon v-show="dengerTab.indexOf('baseInfo') > -1" type="exclamation-circle" />&nbsp;基本信息
          </li>
          <li
            v-show="(!(changeId || changeInit) || ((changeId || changeInit) && changeModels.indexOf(1) > -1)) && !isProjectMember"
            :class="{ clickShow: pageId == 1, dengerBackGround: dengerTab.indexOf('attach') > -1 }"
            @click="handleTogglePage(1)"
          >
            <a-icon v-show="dengerTab.indexOf('attach') > -1" type="exclamation-circle" />&nbsp;附件
          </li>
        </ul>
        <router-view ref="routerpage" @routerCallBack="routerCallBack" />
      </div>
      <div style="position: fixed; bottom: 10px; left:0;width: 100%; display: flex; justify-content: center;z-index:2" v-if="pageId < 8 && !isProjectMember">
        <a-button v-if="pageId > 0" style="margin-right: 15px" class="default" @click="goPre()">上一页面</a-button>
        <a-button
          v-if="[1].indexOf(pageId) == -1 && canDoSave"
          style="margin-right: 15px; color: #fff; background: #1890ff"
          @click="savePage()"
          :loading="btnLoading"
          >保存本页</a-button
        >
        <a-button
          v-if="
            (!changeId && pageId < 1) ||
            (changeId && changeModels.indexOf(pageId) < changeModels.length - 1)
          "
          class="default"
          @click="goNext()"
          >下一页面</a-button
        >
      </div>
    </div>
    <process-user-select :columns="selUserCols" @selectUserConfirm="selectUserConfirm" ref="processUserSelect" />
  </div>
</template>
<script>
import $ from 'jquery'
import Vue from 'vue'
import { ACCESS_TOKEN, USER_INFO } from '@/store/mutation-types'
import { getAction, postAction, getActionAsync } from '@/api/manage'
import { getParamValFromUrl, strNotNull } from '@/utils/common.js'
import { Modal } from 'ant-design-vue'
var autoSaveInterval = null;
const processUsers = [
  {
    class: '62mg',
    users: [
      { label: '部门主管', field: 'deptUser', username: '', realname: '', required: true },
      { label: '科技管理部', field: 'techDeptUser', username: '', realname: '', required: true }
    ],
  }
]
const FTP_KEY = 'ftp'
export default {
  components: {
    HomeNav: () => import('@/components/layouts/HomeNav'),
    ProcessUserSelect: () => import('@/components/tools/projectBuildStup/ProcessUserSelect')
  },
  data() {
    return {
      userinfo: {
        info: this.$store.getters.userInfo,
        module: 'hatchProjectBuildStup',
      },
      hatchProjectBuildId: '',
      projectClass: '',
      projectType: '',
      showBugGet: true,
      hatchProjectBuild: {},
      notShowButGet: ['90'],
      url: {
        getProjectBuildVOWithProjectManagers: '/hatchProject/getProjectBuildVOWithProjectManagers',
        deleteById: '/hatchProject/deleteById',
        publishEngineProject: '/hatchProject/publishEngineProject',
        checkPublishProject: '/hatchProject/checkPublishProject',
        getRequiredAttachCode: '/projectBuild/getRequiredAttachCode',
        getAttachInfo: '/tp/attach/getAttaches',
        getProjectBuildAttachCodeInfos: '/projectBuild/getProjectBuildAttachCodeInfos',
        codeInfo:'/manage/codeInfo/list'
      },
      pageId: 0,
      currentAudit: 'false',
      toDelVisible: false,
      submitAndDel: false,
      selUserCols: [],
      rerunTestVisible: false,
      processDefinitionVersion: '',
      requiredAttachCode: [],
      attaches: [],
      requiredAttachCode: [],
      dengerTab: [],
      confirmMeet: false,
      btnLoading: false,
      canDoSave: false,
      changeModels: [],
      isProjectMember: false,
      changeId: '',
      changeInit: false,
      processAuditExplainShow: false 
    }
  },
  methods: {
    routerCallBack(val) {
      this.changeModels = []
      if (val != null) {
        val.forEach((item) => {
          this.changeModels.push(parseInt(item))
        })
      }
    },
    async submitProject() {
      
      this.dengerTab = []
      if (this.hatchProjectBuildId == null || this.hatchProjectBuildId == '') {
        this.$message.warning('请填写并保存基本信息')
        this.dengerTab.push('baseInfo')
        return
      }
      
      var res = false
      this.btnLoading = true
      if ([1].indexOf(this.pageId) > -1) {
        res = true
      } else if (this.pageId == 0) {
        if (this.hatchProjectBuild != null && this.hatchProjectBuild.status > 1) {
          res = true
        } else {
          //基本信息
          var doSubmit = await this.$refs.routerpage.$children[0].doSubmit()
          console.log('doSubmit:', doSubmit)
          if (doSubmit.id != null && doSubmit.id.trim().length > 0) {
            //保存成功
            this.hatchProjectBuildId = doSubmit.id
            res = true
          }
        }
      } else {
        var doSubmit = await this.$refs.routerpage.doSubmit()
        console.log('doSubmit:', doSubmit)
        if (doSubmit == 2) {
          res = true
        }
      }
      this.btnLoading = false
      
      if (res) {
        //检查必须上传附件
        var flag = false
        if (this.attaches != null) {
          for (var i = 0; i < this.attaches.length; i++) {
            var att = this.attaches[i]
            if (!flag) {
              flag = await this.checkAttach(att)
            }
          }
        }
   
        if (flag) {
          this.dengerTab.push('attach')
          return
        }

        getAction(this.url.getProjectBuildVOWithProjectManagers, { id: this.hatchProjectBuildId })
          .then((res) => {
            if (res.code == 200) {
              this.hatchProjectBuild = res.result
              this.projectClass = this.hatchProjectBuild.projectClass
              this.projectType = this.hatchProjectBuild.hatchProjectTypeSubCategory
              this.doSubmitProject()
            } else {
              this.$message.warning('提交检测-查询立项信息失败:' + res.message)
            }
          })
          .catch((res) => {
            this.$message.warning('提交检测-查询立项信息失败:' + res.message)
          })
      } else {
        var dengerT =
          this.pageId == 0
            ? 'baseInfo': ''
        this.dengerTab.push(dengerT)
      }
    },
    //操作提交
    async doSubmitProject() {
      if (!this.hatchProjectBuild.validResult) {
        this.$message.warning('请完整填写基本信息后，再进行提交')
        this.dengerTab.push('baseInfo')
        return
      }
      var vm = this
      this.btnLoading = true
      getAction(this.url.checkPublishProject, { id: this.hatchProjectBuildId })
        .then((res) => {
          vm.btnLoading = false
          if (res.code == 200) {
            vm.doSubmitPro();
          } else {
            var msg = res.message
            if (msg != null) {
              var start = msg.split('_')[0].split('，')[1]
              if (start == 'baseInfo') {
                this.dengerTab.push('baseInfo')
              }
            }
            this.$message.warning('校验立项信息异常:' + msg.split('_')[1])
          }
        })
        .catch((res) => {
          this.$message.warning('校验立项信息异常:' + res.message)
        })
    },
    checkProjectCycleRules(){
    },
    doSubmitPro(){
      let vm = this
      vm.selectProcessUsers()
    },
    //检查必传附件
    async checkAttach(att) {
      var flag = false
      let ftpKey = new String(FTP_KEY) 
      if (att.required) {
        //获取附件ftpKey
        let ftpRes = await getActionAsync(this.url.codeInfo,{type:this.hatchProjectBuild.hatchProjectTypeSubCategory+'类立项附件FTP',isDel:false,parentid: '1',code:att.code})
                  
        if(ftpRes.success){
            if(ftpRes.result.records.length>0){
              ftpKey = ftpRes.result.records[0].name
            }
        }
        await getActionAsync(this.url.getAttachInfo, {
          dbKey: 'Trd',
          busKey: this.hatchProjectBuildId,
          busField: 'HatchProject',
          busType: 'other',
          ftpKey: ftpKey,
        }).then((res) => {
          if (res.data == null || res.data.length < 1) {
            this.$message.warning('【' + att.name + '】为必传附件类型，请至少上传一个')
            return (flag = true)
          }
        })
      }
      return flag
    },
    //调起流程选人，发起
    selectProcessUsers() {
      var pclass = this.hatchProjectBuild.projectClass

      // 外联咨询 mg
      if (pclass == '62' && this.hatchProjectBuild.hatchProjectTypeSubCategory == 'MG') {
        pclass = '62mg'
      }

      //发起流程
      processUsers.forEach((item) => {
        if (pclass == item.class) {
          this.selUserCols = item.users
        }
      })
      
      this.$refs.processUserSelect.doSelect()
    },
    selectUserConfirm(cols) {
      if (cols != null && cols.length > 0) {
        var data = {}
        cols.forEach((item) => {
          var key = item.field
          data[key] = item.username
        })

        //参数组装完毕，发起流程
        postAction(this.url.publishEngineProject, { id: this.hatchProjectBuild.id, approvalPerson: data })
          .then((res) => {
            if (res.code == 200) {
              this.canEdit = false
              this.submitAndDel = false
              this.$message.success('发起审批流程成功')
              setTimeout(function () {
                this.$router.push('/hatchIndex')
              }, 1000)
            } else {
              this.$message.warning('发起流程失败:' + res.message)
            }
          })
          .catch((res) => {
            this.$message.warning('发起流程异常:' + res.message)
          })
      } else {
        this.$message.warning('未选中操作员')
      }
    },
    getRequiredAttachCode() {
      getAction(this.url.codeInfo, {type:this.hatchprojectBuild.hatchProjectTypeSubCategory +'类必传附件'})
        .then((res) => {
          if (res.code == 200) {
            this.requiredAttachCode = res.result.records || []
            this.initAttaches()
          } else {
            this.$message.warning('查询必填附件失败:' + res.message)
          }
        })
        .catch((res) => {
          this.$message.warning('查询必填附件失败:' + res.message)
        })
    },
    toDelOk() {
      this.toDelVisible = false
      this.btnLoading = true
      getAction(this.url.deleteById, { id: this.hatchProjectBuildId })
        .then((res) => {
          this.btnLoading = false
          if (res.code == 200) {
            this.$message.success('删除项目成功:' + res.message)
            setTimeout(function () {
              this.$router.push('/hatchIndex')
            }, 1500)
          } else {
            this.$message.warning('删除项目失败:' + res.message)
          }
        })
        .catch((res) => {
          this.$message.warning('删除项目异常:' + res.message)
        })
    },
    async getProjectBuild() {
      // debugger
      if (this.hatchProjectBuildId == null || this.hatchProjectBuildId == '') {
        this.canDoSave = true
        this.autoSaveData()
        return null
      }
      var vm = this
      await getActionAsync(this.url.getProjectBuildVOWithProjectManagers, { id: this.hatchProjectBuildId,changeId: this.changeId })
        .then((res) => {
          // debugger
          if (res.code == 200) {
            var currUserId = Vue.ls.get(USER_INFO).username
            var realname = Vue.ls.get(USER_INFO).realname
            vm.hatchProjectBuild = res.result
            vm.projectClass = vm.hatchProjectBuild.projectClass
            vm.projectType = vm.hatchProjectBuild.hatchProjectTypeSubCategory
            //当前操作员是项目经理 在创建中都可以改
            var isManagerOrAssistantSub = vm.hatchProjectBuild.leaders && vm.hatchProjectBuild.leaders.indexOf(realname) >= 0
            if (vm.hatchProjectBuild.status == 1 && (vm.hatchProjectBuild.createUserName == currUserId || isManagerOrAssistantSub)) {
              vm.submitAndDel = true
            }

            //判断是否有编辑保存权限
            if (vm.submitAndDel) {
              vm.canDoSave = true
              if (vm.hatchProjectBuild.status < 2) {
                vm.autoSaveData()
              }
            }
            //vm.getRequiredAttachCode()
          } else {
            vm.$message.warning('查询孵化立项信息失败:' + res.message)
          }
        })
        .catch((res) => {
          vm.$message.warning('查询孵化立项信息失败:' + res.message)
        })
    },
    async autoSaveData() {
      var vm = this 
      if ([1].indexOf(vm.pageId) > -1 || !vm.canDoSave) {
        return
      }
      if(autoSaveInterval!=null){
        clearInterval(autoSaveInterval)
      }
      autoSaveInterval = setInterval(async function () {
        console.log('------------------------auto save--------------------------------'+new Date())
         getAction('/projectBuild/pageFresh', {}).then((res) => {
          console.log('autoSaveData:'+JSON.stringify(res))
        }).catch((res) => {
          console.log('autoSaveData exception:'+JSON.stringify(res))
        })
      }, 1000 * 60 * 30)
    },
    async savePage() {
      this.btnLoading = true
      if (this.pageId == 0) {  //基本信息
        this.handleTogglePage(0)
      } else {
        this.$refs.routerpage.doSubmit()
      }
      this.btnLoading = false
    },
    async goNext() {
      var goPageId = this.pageId
      if (this.changeId) {
        var index = this.changeModels.indexOf(this.pageId) + 1
        console.log('index:' + index)
        goPageId = this.changeModels[index]
      } else {
        goPageId++
      }
      await this.handleTogglePage(goPageId)
    },
    async goPre() {
      var goPageId = this.pageId
      if (this.changeId) {
        var index = this.changeModels.indexOf(this.pageId) - 1
        console.log('index:' + index)
        goPageId = this.changeModels[index]
      } else {
        goPageId--
      }
      await this.handleTogglePage(goPageId)
    },
    showValHist() {
      this.$refs.routerpage.showHist()
    },
    async handleTogglePage(index) {
      if(!this.changeId){
        this.changeId = getParamValFromUrl('changeId')
      }
      // debugger
      let res = false
      console.log('this.pageId:', this.pageId)
      if ([1].indexOf(this.pageId) > -1 || !this.canDoSave) {
        res = true
      } else if (this.pageId == 0) {
        //基本信息
        var doSubmit = await this.$refs.routerpage.$children[0].doSubmit()
        console.log('doSubmit:', doSubmit)
        if (doSubmit.id != null && doSubmit.id.trim().length > 0) {
          //保存成功
          this.hatchProjectBuildId = doSubmit.id
          res = true
        }
      } else {
        var doSubmit = await this.$refs.routerpage.doSubmit()
        console.log('doSubmit:', doSubmit)
        if (doSubmit == 1 || doSubmit == 2) {
          res = true
        }
      }
      console.log('handleTogglePage:' + res)
      var obj = {}
      switch (index) {
        case 0:
          obj = { path: '/hatchProjectbuildstep/baseInfo', query: { projectType: this.projectType } }
          break
          //  case 6:
        case 1:
          obj = { path: '/hatchProjectBuildstep/attachPage', query: { projectLevel: this.hatchProjectBuild.projectLevel } }
          break
      }
      if (res) {
        this.pageId = index
        obj.query.pageId = index
        obj.query.hatchProjectBuildId = this.hatchProjectBuildId
        obj.query.projectClass = this.projectClass
        obj.query.currentAudit = this.currentAudit
        obj.query.canDoSave = this.canDoSave ? 'true' : 'false'
        obj.query.changeId = this.changeId
        this.$router.push(obj)
        this.getProjectBuild()
      } else {
        console.log('跳转失败')
      }
    },
    initAttaches() {
      var vm = this
      getAction(this.url.getProjectBuildAttachCodeInfos, {
        projectType: this.hatchProjectBuild.hatchProjectTypeSubCategory,
        timeNodeCode: '1',
      })
        .then((res) => {
          if (res.code == 200) {
            var result = res.result
            if (result != null) {
              result.forEach((item) => {
                if (vm.requiredAttachCode != null) {
                  vm.requiredAttachCode.forEach((reqAtt) => {
                    if (reqAtt.code == item.code) {
                      item.required = true
                    }
                  })
                }
                this.attaches.push(item)
              })
            }
          } else {
            this.$message.warning('查询附件字典配置失败:' + res.message)
          }
        })
        .catch((res) => {
          this.$message.warning('查询附件字典配置失败:' + res.message)
        })
    },
  },
  mounted() {
    this.hatchProjectBuildId = getParamValFromUrl('hatchProjectBuildId')
    this.projectClass = getParamValFromUrl('projectClass')
    this.projectType = getParamValFromUrl('projectType')
    this.pageId = getParamValFromUrl('pageId')
    if (this.pageId != null && this.pageId != '') {
      this.pageId = parseInt(this.pageId)
    } else {
      this.pageId = 0
    }
    this.isProjectMember = getParamValFromUrl('projectMember')==1 ? true : false
    var currentAudit = getParamValFromUrl('currentAudit')
    if (currentAudit != null && currentAudit.length > 0) {
      this.currentAudit = currentAudit
    }
    this.changeId = getParamValFromUrl('changeId')
    this.changeInit = getParamValFromUrl('changeInit')=='true' ? true : false;
    console.log('changeId:',this.changeId)
    console.log('changeInit:',this.changeInit)
    this.getProjectBuild()
  },
  destroyed(){
    if(autoSaveInterval!=null){
      clearInterval(autoSaveInterval)
    }
  }
}
</script>
<style lang="less" scoped>
/deep/ .ant-btn-primary {
  background-color: #1890ff !important;
}
.dengerBackGround {
  background-color: #faad14 !important;
}
.projectBuildStup {
  height: 100%;
  .navigator {
    min-height: 100%;
    padding: 40px 125px 0;
    background-color: #f5f5f5;
    .left-content {
      width: 100%;
      > ul {
        color: #fff;
        list-style: none;
        display: flex;
        background-color: #31a0e1;
        width: 100%;
        padding: 0;
        a {
          color: #fff;
          &:hover {
            color: #fff;
          }
        }
        li {
          padding: 10px 0px;
          cursor: pointer;
          position: relative;
          font-size: 15px;
          text-align: center;
          min-width: 7vw;
          &:hover {
            background-color: #0581ca;
          }
          &::before {
            content: ' ';
            color: #4fb1eb;
            position: absolute;
            width: 1px;
            height: 23px;
            border-left: 1px solid #4fb1eb;
            right: -1px;
          }
        }
      }
    }
    .clickShow {
      background-color: #0581ca;
      border-bottom: 1px solid #1890ff;
      cursor: pointer;
    }
  }
}
/deep/ .ant-table .ant-table-body::-webkit-scrollbar-track {background-color: #fff;}
.floatNav{
  position: fixed; top: 180px; left: 30px;z-index: 1;
  >button{display: block;margin-bottom: 10px;}
}
@media (max-width: 1080px){  
  div.projectBuildStup .navigator{padding: 40px 30px 0}
  .floatNav{left: 5px;
    >button{padding: 0 2px;font-size:12px;}
  }
}
</style>
